<template>
	<view>
		<scroll-view scroll-x class="bg-white nav">
			<view class="header flex text-center">
				<view class="cu-item flex-sub f-size">
					<button class="cu-btn btn_header_width" @tap="quotes()">引用</button>
					<button class="cu-btn btn_header_width" @tap="selectorder()">查单</button>
					<button class="cu-btn btn_header_width" @tap="selectsource">查看源单</button>
					<button class="cu-btn btn_header_width" @tap="AddBillOrder">保存单据</button>
				</view>
			</view>
			<view class="main">
				<view class="main-box">
					<form>
						<view class="cg-main">
							<view class="">
								<view class="cu-form-group">
									<view class="title">单据编号：</view>
									<input :value="checkdata.BillNo" placeholder="请先建立单据" disabled="true">
									<!-- <view class="title">单据编号：{{checkdata.BillNo}}</view> -->
									<!-- <view class="title">单据编号：{{checkdata.BillNo}}</view> -->
								</view>
								<view class="cu-form-group" @tap="changeShow('QS_Picekr_date',0)">
									<view class="title">单据日期：</view>
									<input :value="checkdata.BillTime" placeholder="点击选择<单据日期>" disabled="true">
									<!-- <view class="title">单据日期：　{{checkdata.BillTime}}</view> -->
									<!-- <view @tap="open()" class="inpt1"> -->
									<!-- timeData.fulldate -->
									<!-- <input disabled="true">{{checkdata.BillTime}}</input> -->
									<!-- </view> -->
								</view>
								<view class="cu-form-group" @tap="clicktoclient">
									<view class="title">供 应 商 ：</view>
									<!-- checkedClientList.ClientName -->
									<input :value="checkdata.BName" disabled="true" placeholder="点击选择<供应商>">
									<view @tap.stop="ckechdempty(1)" class="empty">清空</view>
									<!-- <view class="supplieruser">{{checkdata.BName}}</view> -->

								</view>
								<view class="cu-form-group" @tap="clickopen(2,'仓库')">
									<view class="title">仓　　库：</view>
									<!-- checkedwarehouse.StoreName -->
									<input :value="checkdata.stockName" placeholder="点击选择<仓库>" disabled="true">
									<view @tap.stop="ckechdempty(2)" class="empty">清空</view>
									<!-- <view class="supplieruser">{{checkdata.stockName}}</view> -->
								</view>
								<view class="cu-form-group" @tap="clickopen(3,'业务员')">
									<view class="title">业 务 员 ：</view>
									<!-- checksalesman.OperatorName -->
									<input :value="checkdata.EName" placeholder="点击选择<业务员>" disabled="true">
									<view @tap.stop="ckechdempty(3)" class="empty">清空</view>
									<!-- <view class="supplieruser">{{checkdata.EName}}</view> -->
								</view>
								<view class="cu-form-group">
									<view class="title">备　　注：</view>
									<input placeholder="请输入备注" v-model="BillRemark"></input>
								</view>
								<view class="cu-form-group">
									<view class="title">制 单 人 ：　{{Createuser}}</view>
									<!-- <input class="inpt" disabled="true" name="input" :value="Createuser" style="text-align: right;"></input> -->
								</view>
							</view>
							<view>
								<view class="searchInput">
									<view class="goodFilter">
										<uni-Icons type="search" size="14" style="line-height: 28px;margin-left: 5px;margin-right: 5px;color: #a7aab3;" /><input
										 placeholder="输入条码进行搜索" class="searchOption" confirm-type="search" type="text" @confirm="search()" v-model="searchKey"></input>
										</uni-Icons>
									</view>
									<view class="searchOptions">
										<button class="giveSong" @tap="AddGood()">
											<img src="../../static/image/add.png" alt="">
										</button>
										<button class="getPicture" @tap="tel()"></button>
									</view>
								</view>
							</view>
							<view class="cu-form-group" style="justify-content: space-around;position: fixed;width: 100%;bottom: 0;left: 0;z-index: 999;">
								<!-- <button class="cu-btn  stop text-white" @tap="addSelectGoods" :style="{visibility:isSelectGood?'':'hidden'}">确定商品</button>
                            	<view class="inpt">
                            		<button class="cu-btn  stop text-white" @tap="selectsource" >查看源单</button>
                            	</view>
                            	<button class="cu-btn  stop text-white" @tap="AddBillOrder">保存单据</button> -->
								<!-- <view style="color: #e54d42;font-size: 13px;">未验数：{{noapproved}}</view>
                            	<view style="color: #39b54a;font-size: 13px;">已验数：{{approved}}</view> -->
								<view style="color: #000;font-size: 14px;">商品数量：<span style="color: #39b54a;">{{Goodnum}}</span></view>
								<view style="color: #000;font-size: 14px;">商品金额：<span style="color: red;">{{GoodPrice}}</span></view>
							</view>
							<!--商品明细列表home-->
							<Goodlist :Gooditem="OrderGoodsList" @remove="removeGood" @update="clickEnd"></Goodlist>
							<!--商品明细列表end-->
						</view>
					</form>
				</view>
			</view>
		</scroll-view>
		<!--搜索商品弹窗HOME-->
		<view class="cu-modal " :class="isShowScanModel?'show':''">
			<view class="cu-dialog ls-main">
				<view class="cu-bar bg-ls justify-between">
					<view class="action">
						<view class="cuIcon-info text-white" v-show="false"></view>
					</view>
					<view class="content text-white">选择商品</view>
					<view class="action" @tap="hideGoodModal">
						<text class="cuIcon-close text-white"></text>
					</view>
				</view>
				<view class="padding text-left bg-white ls-contain" style="height: 100%;">
					<scroll-view scroll-y style="height: calc(100% - 1px);">
						<!-- <view class="ls-box" @tap="choosesGoods(index)" v-for="(item,index) in scanGoodList" :key='index' :data-index="index">
						
							<view>{{item.GoodsName}}</view>
						</view> -->
						<!-- scanGoodList -->
						<view class="Good_list" v-for="(item,index) in scanGoodList" @tap="choosesGoods(index)" :key='index' :class="isShowScanModel?'Animation_Good':''">
							<view class="Good_image">
								<img style="width: 100%;height: 100%;border-radius: 50%;" :src="item.Goods_Image_Path1 != '' 
								 &&item.Goods_Image_Path1 != undefined ?'http://192.168.1.51:9000/picture'+item.Goods_Image_Path1:'../../static/image/unUplad.png'"
								 alt="">
							</view>
							<view class="Good_title">
								<view class="Good_content">{{item.GoodsName}}</view>
								<view class="Good_subhead">{{item.BarCode}}</view>
							</view>
							<view class="Good_edit">
								<img src="../../static/image/arrowright.png" alt="">
							</view>
						</view>
					</scroll-view>
				</view>
			</view>
		</view>
		<!--搜索商品弹窗END-->


		<!-- 弹出框HOME -->
		<view class="cu-modal cu_none " :class="modalName=='Modal'?'show':''">
			<view class="cu-dialog">
				<view class="cu-bar bg-white justify-end">
					<view class="content">选择{{listcode}}</view>
					<view class="action" @tap="hideModal">
						<text class="cuIcon-close text-red"></text>
					</view>
				</view>
				<view style="padding: 5px 21px;">
					<view class="search" v-show="listshow == 1"><input class="inpt" @input="monitorClient" v-model="selectCli"
						 placeholder="查询供应商" name="input"></input>
						<span class="search_span" @tap="selectClient()">搜索</span>
					</view>
					<view class="search" v-show="listshow == 2"><input class="inpt" @input="monitorStore" v-model="selectwar"
						 placeholder="查询仓库" name="input"></input>
						<span class="search_span" @tap="selectwarehouse()">搜索</span>
					</view>
					<view class="search" v-show="listshow == 3"><input class="inpt" @input="monitorEmp" v-model="selectsal"
						 placeholder="查询业务员" name="input"></input>
						<span class="search_span" @tap="selectsalesmant()">搜索</span>
					</view>
				</view>
				<scroll-view style="height: 77%;" scroll-y="true">

					<view class="padding-xl" v-show="listshow == 1">
						<!-- 	<view class="search" ><input class="inpt" v-model="selectCli" placeholder="查询客户" name="input"></input>
				<span class="search_span" @tap="selectClient()">搜索</span>
				</view> -->
						<view>
							<!-- this.checkdata["ClientID"] = this.ClientList[e]["ClientID"]
					this.checkdata["BName"] = this.ClientList[e]["ClientName"] -->
							<view class="btn_list" v-show="checkdata.ClientID&&checkdata.BName">{{checkdata.BName}}</view>
							<view class="btn_list" :class="[{'background_color':checkdata.ClientID&&checkdata.BName}]" v-for="(item,index) in ClientList"
							 @tap="checkuser(index)" :key="item.id">{{item.ClientName}}</view>
							<!-- <view class="btn_list">我是选中的供应商</view>	  -->
						</view>
					</view>

					<view class="padding-xl" v-show="listshow == 2">

						<view>
							<view class="btn_list" v-for="(item,index) in StoreList" @tap="checkware(index)" :key="item.id">{{item.StoreName}}</view>
						</view>
					</view>
					<view class="padding-xl" v-show="listshow == 3">

						<view>
							<view class="btn_list" v-for="(item,index) in OperatorList" @tap="checksale(index)" :key="item.id">{{item.OperatorName}}</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</view>
		<!-- 弹出框END -->
		<!-- 日期选择器 -->
		<QSpicker title="请选择日期时间" mode="bottom" type="date" ref="QS_Picekr_date" pickerId="date_1" :dataSet="dateSet"
		 showReset :autoHide="false" contentColor="#33cc33" :lineHeight=".05" @hideQSPicker="hideQSPicker($event)"
		 @showQSPicker="showQSPicker($event)" @confirm="newconfirm($event)" />
		<!-- 侧边抽屉 -->
		<Drawerui Billtype="v1_setting" ref="Drawer" @RemotePrint="RemotePrint"></Drawerui>
	</view>
</template>
<script>
	import allConst from "../../Json.js";
	import uniIcons from '@/components/uni-icon/uni-icon.vue';
	import QSpicker from '@/components/QuShe-picker/QuShe-picker.vue';
	import Drawerui from '@/components/Drawer.vue';
	import * as GetApi from '@/syApis/syHttp/Http.js';
	import * as rules from "@/common/barcodeRules.js";
	import Goodlist from "@/components/selectGoodsItem/GoodList.vue";
	export default {
		// name:"uniIcons",
		data() {
			return {
				date: '',
				isshow: false,
				timeData: {
					clockinfo: '',
					date: '',
					fulldate: '',
					lunar: '',
					month: '',
					range: '',
					year: ''
				},
				index: 0,
				modalName: null,
				BillNo: "", //单据编号
				//单据类型
				BillType: 3,
				IsAdd: 0,
				BillDate: "",
				//订单商品
				OrderGoodsList: [],
				//当前选择的商品
				NowSelectGoods: {},
				//仓库的列表
				StoreList: [],
				temStoreList: [], //临时 用于快速搜索
				//业务员的列表
				OperatorList: [],
				temOperatorList: [], //临时用于快速搜索
				//供应商的列表
				ClientList: [],
				//制单人
				CreateName: uni.getStorageSync("UserName"),
				//税率
				Tax: "",
				//商品列表查看更多标识
				selectLookMore: -1,

				//扫码多商品列表
				scanGoodList: [{
					name: "标题"
				}],
				//当前多商品选择的索引
				current: -1,
				//多规格商品弹框
				isShowScanModel: false,
				//搜索条件
				searchKey: "",
				//单据类型
				BillName: "采购订单",
				//单据类型编号
				BillTypes: 3,
				listcode: '',
				// 选中的供应商
				checkedClientList: [],
				//选中的仓库
				checkedwarehouse: [],
				//选中的业务员
				checksalesman: [],
				// 搜索供应商
				selectCli: '',
				// 搜索的仓库
				selectwar: '',
				// 搜索的业务员
				selectsal: '',
				diy_layer: false, //自定义弹窗显示
				listshow: -1,
				// 页面的数据(包括从其他页面返回的)
				checkdata: {
					ClientID: "",
					BillTime: "",
					ClientName: "",
					stockName: '',
					EName: '',
					BName: ''
				},
				GoodPrice: 0, //商品总金额
				Goodnum: 0, //商品总数量
				approved: 0, //已验数
				noapproved: 0, //未验数
				BillRemark: '', //备注
				isquote: -1, //用于判断是引用单据返回的还是查单返回的
				Createuser: '', //制单人
				dateSet: {
					dateMode: 3,
					dateFormatArray: ['-', '-', ' ', ':', ':']
				},
				setting: [{
					validation: {
						bluetooth: -1,
						long: -1,
						repetition: -1,
						// enter:-1,
						barcode: -1,
						selectd: -1,
						Openquickscan: -1,
						// IsAll:-1,
					}
				}, ],
				approvedlist: [],
				//单据是否直接审核
				isBillCheckQx: false
			}
		},
		components: {
			uniIcons,
			QSpicker,
			Drawerui,
			Goodlist
		},
		onLoad(options) {
			this.getClientList(); //供应商
			this.GetOperatorMessage(); //业务员
			this.GetStoreMessage(); //仓库
			this.Createuser = uni.getStorageSync("UserName");
		},
		onShow() {
			this.$eventHub.$off('returnedgoods');
			this.$eventHub.$off('psfire');
			this.$eventHub.$off('Addfires');
			this.imputed()
			var that = this;
			let SystemSettingInfo = uni.getStorageSync("SystemSettingInfo", ""); //存储系统设置
			if (SystemSettingInfo != "") {
				SystemSettingInfo = JSON.parse(SystemSettingInfo);
				SystemSettingInfo.forEach((item, index) => {
					if (item.SystemName == '单据是否直接审核') {
						if (item.Value == "1") {
							that.isBillCheckQx = true;
						}
					}
				});
			}
		},
		created() {
			let date = new Date();
			this.BillDate = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
			//判断本地是否存在配置 如果不存在则初始化默认配置
			var that = this
			// var setting = []
			//  setting =  JSON.parse(uni.getStorageSync("v1_setting",""));
			// console.log("读取本地配置")
			// console.log(setting.validation)
			// if(setting.validation1 == ''|| setting.validation1 == undefined){
			// 	// setting.push(this.setting)
			// 	// console.log(setting)
			// 	uni.setStorageSync(JSON.stringify(setting))
			// }
			// uni.getStorage({
			//    key:"setting",
			//   success(e){
			//      e.data
			//      var valida = JSON.parse(e.data)
			// 	 console.log(valida.validation)
			// 	 // var setting = {
			// 		//  validation1:
			// 	 // }
			//      console.log(valida.validation1)
			// 	 if(valida.validation1 == ''||valida.validation1==undefined){
			// 		  var data = JSON.stringify(this.setting)
			// 		  console.log(data)
			// 		  uni.setStorage({
			// 		  key:"setting",
			// 		  data:data
			// 		  })
			// 	 }else{
			// 		 that.setting.validation1 = valida.validation1
			// 	 }

			//     }
			// })
		},
		methods: {
			// 跳转到引用上级单据
			quotes: function() {
				var that = this
				this.$eventHub.$on('returnedgoods', function(data) {
					//console.log('返回成功的参数')
					var dataarray = data
					that.OrderGoodsList = []
					that.checkdata = []
					that.BillRemark = ''
					console.log('-------我是引用上级单据返回的--------')
					console.log(dataarray)
					dataarray["BillTime"] = that.timesubstr(dataarray["BillTime"])
					that.checkdata = dataarray
					//console.log(dataarray.SourceBillName)
					that.isquote = 1;
					that.BillNo = dataarray.BillNo; //单据编号
					// if(that.isquote == 1){
					that.details(that.checkdata.BillID)
					// }else if(that.isquote == 2){
					// 	that.selectbill(that.checkdata.BillID)
					// }
					that.$eventHub.$off('returnedgoods');
				});
				uni.navigateTo({
					url: '../Purchasereturn/quote_children/quote_children'
				});
			},
			imputed: function() {
				// 计算商品的价格
				var tmpprice = 0; //商品总金额
				var tmpnum = 0; //商品数量
				for (var i in this.OrderGoodsList) {
					tmpprice = parseFloat(tmpprice) + parseFloat(this.OrderGoodsList[i].Amount)
					tmpnum = parseFloat(tmpnum) + parseFloat(this.OrderGoodsList[i].Qty)
				}

				this.GoodPrice = parseFloat(tmpprice).toFixed(2)
				this.Goodnum = tmpnum;
			},
			//查看源单明细
			selectsource: function() {
				//console.log('跳转页面携带的参数')
				//console.log(this.OrderGoodsList)
				if(this.isquote == -1){
					// GetApi.showTip("请选择单据");
					uni.showToast({
						title:'请选择单据!',
						icon:'none',
						position:'center'
					})
					return
				} 
				uni.navigateTo({
					url: '../Purchasereturn/source_children/selectsource?id=' + this.checkdata.BillID
					+ '&BillNo=' + this.checkdata.BillNo +'&OrderGoodsList=' + JSON.stringify(this.OrderGoodsList) + "&isquote=" + this.isquote
					// JSON.stringify()

				});
			},
			//跳转到查单界面
			selectorder: function() {
				var that = this
				this.$eventHub.$on('psfire', function(data) {
					//console.log('返回成功的参数')
					var dataarray = data
					that.OrderGoodsList = []
					that.checkdata = []
					that.BillRemark = ''
					console.log('--------我是查单返回的--------')
					console.log(dataarray)
					dataarray["BillTime"] = that.timesubstr(dataarray["BillTime"]);
					that.checkdata = dataarray;
					that.BillRemark = dataarray.Comment;
					that.isquote = 2;
					//console.log(dataarray.SourceBillName)
					that.BillNo = dataarray.BillNo; //单据编号
					// if(that.isquote == 1){
					// 	that.details(that.checkdata.BillID)
					// }else if(that.isquote == 2){
					that.selectbill(that.checkdata.BillID)
					// }
					that.$eventHub.$off('psfire');
				});
				uni.navigateTo({
					url: '../Purchasereturn/select_children/select_children'
				});
			},
			//跳转选择供应商界面
			clicktoclient: function() {
				var that = this
				this.$eventHub.$on('clientListen', function(data) {
					console.log('返回的参数')
					// JSON.parse(data)
					var checkd = JSON.parse(data)
					that.checkdata.ClientID = checkd["ClientID"]
					that.checkdata.BName = checkd["ClientName"]
					console.log(JSON.parse(data))
					console.log(that.checkdata.ClientID)
					console.log(that.checkdata.BName)
					that.$eventHub.$off('clientListen');
				});
				uni.navigateTo({
					// pages/clientSelect/clientSelect
					url: '../clientSelect/clientSelect?isClient=1'
				});
			},
			//清空
			ckechdempty: function(nav) {
				console.log('点击了清空')
				if (nav == 1) {
					this.checkdata.ClientID = "";
					this.checkdata.BName = "";
				} else if (nav == 2) {
					// console.log('执行了')
					// console.log(this.checkdata.StoreID)
					// console.log(this.checkdata.stockName)

					this.checkdata.StoreID = "";
					this.checkdata.stockName = "";
					// console.log(this.checkdata.stockName)
					// console.log(this.checkdata.StoreID)
				} else if (nav == 3) {
					this.checkdata.EmpID = "";
					this.checkdata.EName = "";
				}
			},
			//监听仓库
			monitorStore(evt) {
				var val = evt.detail.value; //取到监听的值
				console.log(val)
				var resarr = []
				// ClientName
				if (val != "") {
					for (var i in this.StoreList) {
						var string1 = this.StoreList[i].StoreName
						var string2 = this.StoreList[i].BranchName
						// console.log(string1.indexOf(val))
						// var string2 = this.ClientList[i].Address
						// if(string1.valueOf(val) >=0 ||string2.valueOf(val)>=0){
						if (string1.indexOf(val) >= 0 || string2.indexOf(val) >= 0) {
							resarr.push(this.StoreList[i])
						}
					}
					if (resarr.length == 0) {
						GetApi.showTip("查无数据");
						this.StoreList = []
					} else {
						this.StoreList = resarr
					}
					// this. = resarr
				} else {
					this.StoreList = this.temStoreList
				}
			},
			//监听业务员
			monitorEmp(evt) {

				var val = evt.detail.value; //取到监听的值
				console.log(val)
				console.log(this.OperatorList)
				var resarr = []
				// ClientName
				if (val != "") {
					for (var i in this.OperatorList) {

						console.log(this.OperatorList[i])
						var string1 = this.OperatorList[i].OperatorName
						var string2 = this.OperatorList[i].Address
						// console.log(string1.indexOf(val))
						// var string2 = this.ClientList[i].Address
						// if(string1.valueOf(val) >=0 ||string2.valueOf(val)>=0){
						if (string1.indexOf(val) >= 0 || string2.indexOf(val) >= 0) {
							resarr.push(this.OperatorList[i])
						}
						if (resarr == "") {
							GetApi.showTip("查无数据");
							this.OperatorList = []
						} else {
							this.OperatorList = resarr
						}
					}
					// this.OperatorList = resarr
				} else {
					this.OperatorList = this.temOperatorList
				}
			},
			//关闭弹窗
			closemodel: function() {
				this.isshow = false
			},
			//显示选择日期界面
			changeShow(name, type) {

				this.$refs[name].show();
				this.dateName = name;
			},
			showQSPicker(res) {
				console.log(res);
			},
			hideQSPicker(res) {

			},
			newconfirm(res) {

				var data = GetApi.splitdate(res.data); //处理的日期
				console.log("处理的日期")
				console.log(data)
				// var fulldata = res.data
				this.checkdata.BillTime = data
				console.log(res)
				this.$refs[this.dateName].hide();
			},
			//打开选择的弹窗
			clickopen: function(evt, msg) {
				this.listshow = Number(evt);
				this.listcode = msg;
				this.modalName = 'Modal'
			},
			// 搜索的供应商
			selectClient: function() {
				//console.log(this.selectCli)
				this.getClientList(this.selectCli)

			},
			// 搜索的仓库
			selectwarehouse: function() {
				//console.log(this.selectwar)
				this.GetStoreMessage(this.selectwar)
			},
			// 搜索的业务员
			selectsalesmant: function() {
				//console.log(this.selectsal)
				this.GetOperatorMessage(this.selectsal)
			},
			// 选中的供应商
			checkuser: function(e) {
				this.checkdata["ClientID"] = this.ClientList[e]["ClientID"]
				this.checkdata["BName"] = this.ClientList[e]["ClientName"]
				this.modalName = null
			},
			// 选中的仓库
			checkware: function(e) {
				// this.checkedwarehouse = this.StoreList[e]
				// 仓库StoreID stockName
				// this.checklist = e
				this.checkdata["StoreID"] = this.StoreList[e]["StoreID"]
				this.checkdata["stockName"] = this.StoreList[e]["StoreName"]
				this.modalName = null
				//console.log('打印的参数')
				//console.log(this.checkdata)
			},
			// 选中的业务员
			checksale: function(e) {
				// 业务员 EmpID EName
				// this.checksalesman = this.OperatorList[e]
				this.checkdata["EmpID"] = this.OperatorList[e]["OperatorID"]
				this.checkdata["EName"] = this.OperatorList[e]["OperatorName"]
				this.modalName = null
				//console.log('打印的参数')
				//console.log(this.checksalesman)
			},
			choosesGoods(index) {
				var that = this
				if (this.checkdata.StoreID == "" || this.checkdata.StoreID == undefined) {
					GetApi.showTip('请先建立单据!')
					return
				}
				// that.OrderGoodsList.push(that.scanGoodList[index]);
				this.isShowScanModel = false;
				console.log(that.scanGoodList[index]);
				that.scanGoodList[index]["stockName"] = this.checkdata.stockName; //赋值表头仓库
				that.scanGoodList[index]["StoreID"] = this.checkdata.StoreID; //赋值表头仓库
				that.toredact(that.scanGoodList[index])
			},
			// 搜索选择商品后跳转编辑页面 ----不是直接添加
			toredact(event) {
				var that = this;
				var toevent = event
				this.$eventHub.$on('fireredact', function(data) {
					// that.OrderGoodsList[data.index] = JSON.parse(data.NewGoodInfo);
					// that.selectLookMore = -1;
					that.GoodsEach(JSON.parse(data))
					console.log(data)
					console.log('返回成功的参数')
					that.$eventHub.$off('fireredact');
				});
				uni.setStorageSync("source",JSON.stringify(this.approvedlist))
				uni.setStorageSync("Order",JSON.stringify(this.OrderGoodsList))
				uni.navigateTo({
					// url: "../SelectedGoods/SelectedGoods?StoreID=" + this.checkdata.StoreID+"&name=采购入库单"+"&BillID="+this.checkdata.BillID+
					// "&stockName="+this.checkdata.stockName
					url: "../SelectedGoods/Goodredact?goodData=" + JSON.stringify(toevent) +
						"&name=采购退货单" + "&ClientID=" + this.checkdata.ClientID +
						"&StoreID=" + this.checkdata.StoreID
						// +"&source=" + JSON.stringify(this.approvedlist)
						// +"&Order="+JSON.stringify(this.OrderGoodsList)
						+"&isquote="+this.isquote
						
				});
			},

			search() {
				if (this.checkdata.StoreID == ""||this.checkdata.StoreID==undefined) {
					uni.showToast({
						title: "请先选择仓库或建立单据",
						icon:'none'
					});
					return;
				};
				if(this.isShowScanModel == true){
					console.log('打印----')
					return
				}
				this.GetBarcodeGoodsMessageModel(this.searchKey);
			},
			//扫码获取商品
			tel: function() {
				this.current = -1;
				// 调起条码扫描
				var _this = this;
				uni.scanCode({
					scanType: 'barCode',
					success: function(res) {
						_this.GetBarcodeGoodsMessageModel(res.result);
						//console.log('条码类型：' + res.scanType);
						//console.log('条码内容：' + res.result);
					},
					fail(e) {
						//console.log(e);
					}
				});
			},
			//通过条码扫描商品
			GetBarcodeGoodsMessageModel(barcode) {
				let Model = "";
				var config = this.GetConfig()
				var bar = JSON.parse(uni.getStorageSync("BarCode", ""))
				console.log('配置信息')
				console.log(config.selectd)
				// 0代表启用条码规则
				if (config.barcode == 0) {
					var code = rules.getRulesStr(true, bar, barcode)
					barcode = code.searchKey
				}
				if (config.selectd == 1) {
					Model = "%like"
				} else if (config.selectd == 2) {
					Model = "like%"
				} else {
					Model = "like"
				}
				let data = {
					// this.BillName
					BillName: "采购退货单",
					BarCode: barcode,
					Model: Model + ""
				};
				var that = this;
				GetApi.GetBarcodeGoodsMessageModel(data, function(res) {
					//console.log(res.data.ResultMsg);
					// GetApi.showTip(res.data.ResultMsg);
					if (res.data.ResultMsg != '') {
						if (res.data.ResultMsg.length == 0) {
							GetApi.showTip("查无数据");
							return
						}
						var GoodList = res.data.ResultMsg;
						for (var i in GoodList) {
							GoodList[i].urate = GoodList[i].URate || GoodList[i].urate
						}
						if (config.Openquickscan == 0) {
							if(GoodList[0].IsBatch == true){
								GetApi.showTip("批号商品不允许快速扫描!");
							}else{
								that.prices(GoodList[0])
							}
						} else {
							if(GoodList.length > 1){
								that.isShowScanModel = true;
								that.scanGoodList = GoodList
							}else{
								that.scanGoodList = GoodList
								that.choosesGoods(0)
							}
						}
						that.searchKey = ''
						// that.isShowScanModel = true;
						// that.scanGoodList = res.data.ResultMsg;
						//console.log("Ji");
					} else if (res.data.ResultMsg == "") {
						GetApi.showTip("查无数据");
					} else if (res.data.ErrorMsg == "获取登录信息失败") {

					} else {

					}

				})
			},
			//价格跟踪
			prices:function(Gooddata){
				// //console.log('打印=============')
				console.log('执行了价格跟踪')
				console.log(Gooddata)
				var that = this;
				let data = {
					// this.NowSelectGoods
					ClientID :that.checkdata["ClientID"],
					StoreID:that.checkdata["StoreID"],
					BillName: "采购退货单",
					GoodsID:Gooddata.GoodsID+"",
					UnitID:Gooddata.UnitID+"",
					URate:Gooddata.urate+"",
					VIPID:''
				}
				 GetApi.XH_Get_PriceFollowMessage(data, function(res) {
					if (res.state) {
						if (res.data.ErrorMsg == "获取登录信息失败") {
							GetApi.showTip("登录超时");
						} else if (res.data.ErrorMsg != "") {
							GetApi.showTip(res.data.ErrorMsg);
						} else {
							// console.log('价格跟踪的第一个')
							// console.log(parseFloat(res.data.ResultMsg[0].Price))
							// // res.data.ResultMsg[0]["Price"] =  
							// Gooddata.Price = parseFloat(res.data.ResultMsg[0].Price)
							// //赋值默认
							// Gooddata.StoreID = that.checkdata["StoreID"];
							// Gooddata.IsGift = "0";
							// Gooddata.Tax = "0";
							// Gooddata.Discount = "100";
							// Gooddata.Qty = "1";
							// Gooddata.Amount = that.computPrice(Gooddata);
							// console.log('计算后的数组')
							// console.log(Gooddata)
							Gooddata.StoreID = that.checkdata["StoreID"];
							var list =  that.approvedlist;
							var status = false
							var status_Good = null
							for(var i in list){
								if(CommonFun.isidentical(list[i],Gooddata) == true){
									status = true
									status_Good = list[i]
									// IsGift = list[i]["IsGift"]
									// Tax = list[i]["Tax"]
									// Discount = list[i]["Discount"]
									break
								}
							}
							if(status == true){
								Gooddata.IsGift = status_Good.IsGift == "0" ||  status_Good.IsGift == undefined || 
								  status_Good.IsGift == false ||  status_Good.IsGift == ""?"0":'1';
								Gooddata.Tax = status_Good.Tax;
								Gooddata.Discount = status_Good.Discount;
								Gooddata.Price = status_Good.Price;
								
								// Gooddata.BatchNo = this.isnulls(this.timesubstr(status_Good.BatchNo))
								// Gooddata.ProductionDate = this.isnulls(this.timesubstr(status_Good.ProductionDate))
								// Gooddata.validityDate = this.isnulls(this.timesubstr(status_Good.validityDate))
							}else{
								Gooddata.IsGift = "0";
								Gooddata.Tax = "0";
								Gooddata.Discount = "100";
								Gooddata.Price = parseFloat(res.data.ResultMsg[0].Price);
								// Gooddata.Qty = "1";
							}
							Gooddata.Qty = "1";
							Gooddata.Amount = that.computPrice(Gooddata);
							uni.hideLoading()
							var result = that.Isbill(Gooddata)
									//如果等于1表示不存在需要提示用户是否继续添加
											if(result.Isbills == 0){
												GetApi.showConfirm("源单明细中没有此商品,是否添加？", function(state) {
													if (state) {
														Gooddata.hasqty = 0
														that.GoodsEach(Gooddata)
													}
												})
											}else if(result.Isgreater== 1){
												GetApi.showConfirm("录入的数量大于源单数量,是否添加？", function(state,) {
													if (state) {
														Gooddata.hasqty = 0
														that.GoodsEach(Gooddata)
													}
												})
											}else{
												that.GoodsEach(Gooddata)
											}
						}
					} else {
							GetApi.showTip("服务器错误!");
					}
				});
			},
			isnulls:function(e){
				return e == "" || typeof e == 'undefined' ?"":e
			},
			//判断录入数量是否大于源单数量
			Isbill:function(data){
				var result = {
					Isbills:0,
					Isgreater:0,
				}
				var tmpGoods = this.approvedlist
				console.log('数组对比');
				console.log(data);
				console.log(tmpGoods)
				var that = this;
				for(var j in tmpGoods){
					    // data["IsGift"] = data["IsGift"] == "0"?false:true;
						tmpGoods[j]["IsGift"] = tmpGoods[j]["IsGift"] == false || "0"?"0":"1";
						tmpGoods[j]["Qty"] = parseFloat(tmpGoods[j]["Qty"])
					    console.log('-------这是对比HOME---------');
					    console.log('这是商品ID', "选中" + data["GoodsID"], "源单" + tmpGoods[j]["GoodsID"]);
					    console.log('这是商品名称', "选中" + data["GoodsName"], "源单" + tmpGoods[j]["GoodsName"]);
					    console.log('这是单位', "选中" + data["UnitID"], "源单" + tmpGoods[j]["UnitID"]);
					    console.log('这是仓库', "选中" + data["StoreID"], "源单" + tmpGoods[j]["StoreID"]);
					    console.log('这是赠品', "选中" + data["IsGift"], "源单" + tmpGoods[j]["IsGift"]);
					    console.log('这是批号', "选中" + that.isnulls(data["BatchNo"]), "源单" + that.isnulls(tmpGoods[j]["BatchNo"]))
					    console.log('这是单价', "选中" + parseFloat(data["Price"]), "源单" + parseFloat(tmpGoods[j]["Price"]));
					    console.log('这是税率', "选中" + data["Tax"], "源单" + tmpGoods[j]["Tax"]);
					    console.log('这是折扣', "选中" + data["Discount"], "源单" + tmpGoods[j]["Discount"]);
					    console.log('这是生产日期', "选中" + that.isnulls(that.timesubstr(data["validityDate"])), "源单" + that.isnulls(that.timesubstr(tmpGoods[j]["validityDate"])))
					    console.log('这是有效日期', "选中" + that.isnulls(that.timesubstr(data["ProductionDate"])), "源单" + that.isnulls(that.timesubstr(tmpGoods[j]["ProductionDate"])))
						if(tmpGoods[j]["GoodsName"] == data["GoodsName"] 
						   && tmpGoods[j]["GoodsID"] == data["GoodsID"] 
						   && tmpGoods[j]["StoreID"] == data["StoreID"]
						   && tmpGoods[j]["UnitID"] == data["UnitID"]
						   && tmpGoods[j]["IsGift"] == data["IsGift"]
						   && that.isnulls(tmpGoods[j]["BatchNo"]) == that.isnulls(data["BatchNo"])
						   && parseFloat(tmpGoods[j]["Price"]) == parseFloat(data["Price"])
						   && tmpGoods[j]["Tax"] == data["Tax"]
						   && tmpGoods[j]["Discount"] == data["Discount"]
						   && that.isnulls(that.timesubstr(tmpGoods[j]["ProductionDate"])) == that.isnulls(that.timesubstr(data["ProductionDate"]))
						   && that.isnulls(that.timesubstr(tmpGoods[j]["validityDate"])) == that.isnulls(that.timesubstr(data["validityDate"]))
							){
							//console.log('存在');
							result.Isbills = 1;
							//console.log(data["Qty"])
							//console.log(parseFloat(this.tmpGoods[i]["Qty"]))
							console.log('是源单商品')
							console.log('输入的数量')
							console.log(parseFloat(data["Qty"]))
							console.log('源单的数量')
							console.log(tmpGoods[j]["Qty"])
							result.Isgreater = that.isgreater(tmpGoods[j])
							// for()
							// if(parseFloat(data["Qty"])>parseFloat(tmpGoods[j]["Qty"])){
							// 	result.Isgreater = 1;
							// }
						}
				}
				return result
			},
			// 判断数量是否大于源单数量
			isgreater:function  (data) {
				var Good = this.OrderGoodsList;//
				var that = this;
				var status = 0;
				console.log('存在的商品')
				console.log(Good)
				console.log('源单的商品')
				console.log(data)
				for(var i in Good){
					// data["IsGift"] = data["IsGift"] == "0"?false:true;
					data["IsGift"] = data["IsGift"] == false || "0"?"0":"1";
					data["Qty"] = parseFloat(data["Qty"])
					console.log('-------这是对比HOME---------');
					console.log('这是商品ID', "选中" + Good[i]["GoodsID"], "源单" + data["GoodsID"]);
					console.log('这是商品名称', "选中" + Good[i]["GoodsName"], "源单" + data["GoodsName"]);
					console.log('这是单位', "选中" + Good[i]["UnitID"], "源单" + data["UnitID"]);
					console.log('这是仓库', "选中" + Good[i]["StoreID"], "源单" + data["StoreID"]);
					console.log('这是赠品', "选中" + Good[i]["IsGift"], "源单" + data["IsGift"]);
					console.log('这是批号', "选中" + that.isnulls(Good[i]["BatchNo"]), "源单" + that.isnulls(data["BatchNo"]))
					console.log('这是单价', "选中" + parseFloat(Good[i]["Price"]), "源单" + parseFloat(data["Price"]));
					console.log('这是税率', "选中" + Good[i]["Tax"], "源单" + data["Tax"]);
					console.log('这是折扣', "选中" + Good[i]["Discount"], "源单" + data["Discount"]);
					console.log('这是生产日期', "选中" + that.isnulls(that.timesubstr(Good[i]["validityDate"])), "源单" + that.isnulls(that.timesubstr(data["validityDate"])))
					console.log('这是有效日期', "选中" + that.isnulls(that.timesubstr(Good[i]["ProductionDate"])), "源单" + that.isnulls(that.timesubstr(data["ProductionDate"])))
					if(Good[i]["GoodsName"] == data["GoodsName"] 
					   && Good[i]["GoodsID"] == data["GoodsID"] 
					   && Good[i]["StoreID"] == data["StoreID"]
					   && Good[i]["UnitID"] == data["UnitID"]
					   && Good[i]["IsGift"] == data["IsGift"]
					   && that.isnulls(Good[i]["BatchNo"]) == that.isnulls(data["BatchNo"])
					   && parseFloat(Good[i]["Price"]) == parseFloat(data["Price"])
					   && Good[i]["Tax"] == data["Tax"]
					   && Good[i]["Discount"] == data["Discount"]
					   && that.isnulls(that.timesubstr(Good[i]["ProductionDate"])) == that.isnulls(that.timesubstr(data["ProductionDate"]))
					   && that.isnulls(that.timesubstr(Good[i]["validityDate"])) == that.isnulls(that.timesubstr(data["validityDate"]))
						){
							console.log('数量对比--------------------------------------------------------------------')
							console.log('商品',Good[i]["Qty"])
							console.log('源单',parseFloat(data["UNQTY"]))
							if(parseFloat(Good[i]["Qty"]) >= parseFloat(data["UNQTY"])){
								console.log('等于录-------------------------------------------')
								status = 1;
								break
							}
					}
				}
				return status
			},
			//计算金额
			computPrice(data){
				var Price = 0;
				//console.log('进来的参数')
				//console.log(item)
				// parseFloat((item.PFPrice*item.Qty*(item.Discount/100)*(1+item.Tax/100))).toFixed(2);
				Price = parseFloat((data.Price*data.Qty*(data.Discount/100)*(1+data.Tax/100))).toFixed(2);
				//console.log('计算后的金额')
				//console.log(Price)
				
				var Pr =Math.round(Price * 100) / 100;
				// console.log("555550",Pr)
				return Pr;
			},
			removeGood(e) {
				var del = this.OrderGoodsList
				del.splice(e.index, 1)
				this.OrderGoodsList = del
				this.imputed()
			},
			clickEnd: function(e) {
				var that = this;
				this.$eventHub.$on('updateGood', function(data) {
					console.log('返回成功的参数')
					console.log(data.index)
					var Goodjson = JSON.parse(data.NewGoodInfo); //返回的对象
					that.forupdate(Goodjson, data.index)
					that.$eventHub.$off('updateGood');
				});
				this.OrderGoodsList[e.index]["ClientID"] = this.checkdata.ClientID
				uni.navigateTo({
					url: "../SelectedGoods/selectGoodInfo?goodData=" + JSON.stringify(this.OrderGoodsList[e.index]) +
						"&selectIndex=" + e.index + "&source=" + JSON.stringify(this.approvedlist)
						+ "&Bname=采购退货单"
				});
			},
			// 需要单独赋值
			forupdate: function(item, index) {
				this.OrderGoodsList[index].StoreID = item.StoreID;
				this.OrderGoodsList[index].stockName = item.stockName;
				this.OrderGoodsList[index].UnitID = item.UnitID;
				this.OrderGoodsList[index].IsGift = item.IsGift;
				this.OrderGoodsList[index].BatchNo = item.BatchNo;
				this.OrderGoodsList[index].ProductionDate = item.ProductionDate;
				this.OrderGoodsList[index].validityDate = item.validityDate;
				this.OrderGoodsList[index].Tax = item.Tax;
				this.OrderGoodsList[index].Price = parseFloat(item.Price);
				this.OrderGoodsList[index].Discount = item.Discount;
				this.OrderGoodsList[index].Qty = parseFloat(item.Qty); //数量修改
				this.OrderGoodsList[index].Remark = item.Remark;
				this.OrderGoodsList[index].Amount = parseFloat(item.Amount).toFixed(2);
				this.source_Good()
			},


			//获取供应商列表
			getClientList: function(e) {
				let data = {};
				// 当e不为空时,为搜索
				if (e == "" || e == undefined) {
					data = {
						Filter: "IsClient<>1"
					}
				} else {
					this.checkedClientList = []
					data = {
						// "(ClientName●like●'%" + cc + "%')"ClientCode
						Filter: "IsClient<>1" + " and " + "(" + "ClientName●like●'%" + e + "%'" + " or " + "ClientCode●like●'%" + e +
							"%'" + ")"
					}
				}
				var that = this;
				GetApi.GetClientPurMessage(data, function(res) {
					if (res.state) {
						if (res.data.ErrorMsg == "获取登录信息失败") {
							GetApi.showTip("登录超时");
						} else if (res.data.ErrorMsg != "") {
							GetApi.showTip(res.data.ErrorMsg);
						} else if (res.data.ResultMsg != "" && res.data.TipsMsg == "OK") {
							//console.log('不为空')
							that.ClientList = res.data.ResultMsg;
						} else {
							//console.log('为空')
							that.ClientList = []
							that.diy_layer = true
							setTimeout(function() {
								that.diy_layer = false
							}, 1600)
							// uni.showToast({
							// 	icon: 'none',
							// 	position: 'bottom',
							// 	title: "查无数据"
							// });
							// GetApi.showTip("查无数据");
						}
					} else {
						GetApi.showTip("服务器错误!");
					}
				});
			},
			//获取业务员列表
			GetOperatorMessage: function(e) {
				let data = {};
				// 当e不为空时,为搜索
				if (e == "" || e == undefined) {
					data = {
						Filter: ""
					}
				} else {
					this.OperatorList = []
					data = {
						// "(ClientName●like●'%" + cc + "%')"ClientCode
						Filter: "(" + "OperatorName●like●'%" + e + "%'" + " or " + "OperatorCode●like●'%" + e + "%'" + ")"
					}
				}
				var that = this;
				GetApi.GetOperatorMessage(data, function(res) {
					if (res.state) {
						if (res.data.ErrorMsg == "获取登录信息失败") {
							GetApi.showTip("登录超时");
						} else if (res.data.ErrorMsg != "") {
							GetApi.showTip(res.data.ErrorMsg);
						} else if (res.data.ResultMsg != "" && res.data.TipsMsg == "OK") {
							that.OperatorList = res.data.ResultMsg;
							that.temOperatorList = res.data.ResultMsg;
						} else {
							that.OperatorList = []
							that.diy_layer = true
							setTimeout(function() {
								that.diy_layer = false
							}, 1600)
						}
					} else {
						GetApi.showTip("服务器错误!");
					}
				});
			},
			//商品修改事件监听
			AddListens() {
				var _this = this;
				this.$eventHub.$on('fireData', function(data) {
					_this.OrderGoodsList[data.index] = JSON.parse(data.NewGoodInfo);
					//console.log(_this.OrderGoodsList);
					//console.log(JSON.parse(data.NewGoodInfo));
					// _this.NowSelectGoods = GoodsItem;
					// _this.SelectStockNum(GoodsItem.GoodsID)
					// _this.OrderGoodsList =  GoodsItem;
					// //console.log(GoodsItem); 
					_this.selectLookMore = -1;
					_this.$eventHub.$off('fireData');
				});
			},
			//获取仓库
			GetStoreMessage: function(e) {
				let data = {};
				// 当e不为空时,为搜索
				if (e == "" || e == undefined) {
					data = {
						Filter: ""
					}
				} else {
					this.OperatorList = []
					data = {
						// "(ClientName●like●'%" + cc + "%')"ClientCode
						Filter: "(" + "StoreName●like●'%" + e + "%'" + " or " + "BranchName●like●'%" + e + "%'" + ")"
					}
				}
				var that = this;
				GetApi.GetStoreMessage(data, function(res) {
					if (res.state) {
						if (res.data.ErrorMsg == "获取登录信息失败") {
							GetApi.showTip("登录超时");
						} else if (res.data.ErrorMsg != "") {
							GetApi.showTip(res.data.ErrorMsg);
						} else if (res.data.ResultMsg != "" && res.data.TipsMsg == "OK") {
							that.StoreList = res.data.ResultMsg;
							that.temStoreList = res.data.ResultMsg;
						} else {
							that.StoreList = []
							that.diy_layer = true
							setTimeout(function() {
								that.diy_layer = false
							}, 1600)
						}
					} else {
						GetApi.showTip("服务器错误!");
					}
				});
			},
			open() {
				this.$refs.calendar.open();
			},
			confirm(e) {
				// var fulldate = e.detail.fulldate
				// //console.log(e.detail.fulldate);
				var that = this
				var fulldata = e.fulldate
				that.checkdata.BillTime = fulldata
				// that.checkdata = Object.assign(that.checkdata);
				//console.log(this.checkdata.BillTime)
			},
			AddGood() {
				if (this.checkdata.StoreID == "" || this.checkdata.StoreID == undefined) {
					uni.showToast({
						position: 'bottom',
						title: '请先选择仓库',
						icon: 'none',
						// image:'../../static/image/Warning.png',
						style: "z-index:9999",
						// mask:false,
						// duration:5000,
					});
					return;
				};
				var that = this;
				this.$eventHub.$on('Addfires', function(data) {
					let GoodsItem = JSON.parse(data);
					that.GoodsEach(GoodsItem)
					console.log('选择商品返回的参数')
					console.log(GoodsItem)
					console.log('返回成功后执行')
					that.$eventHub.$off('Addfires');
				});
				if(this.isquote == 2){
					this.checkdata.Qty = this.checkdata.UNQTY
				}
				uni.setStorageSync("Detail",JSON.stringify(this.approvedlist))
				uni.setStorageSync("Order",JSON.stringify(this.OrderGoodsList))
				uni.navigateTo({
					url: "../SelectedGoods/SelectedGoods?StoreID=" + this.checkdata.StoreID + "&name=采购退货单"
					    // +"&Detail=" + JSON.stringify(this.approvedlist) 
					    +"&ClientID=" + this.checkdata.ClientID
					    +"&stockName=" + this.checkdata.stockName
						// +"&Order="+JSON.stringify(this.OrderGoodsList)
						+"&isquote="+this.isquote
						
				});

				// url: "../SelectedGoods/SelectedGoods?StoreID=" + this.checkdata.StoreID+"&name=采购入库单"+
				// "&stockName="+this.checkdata.stockName+"&Detail="+JSON.stringify(this.approvedlist)
				// +"&ClientID="+this.checkdata.ClientID
			},
			
			//添加商品
			GoodsEach(Goods){
				// var 
				var status = false//用于判断是否存在
				var that = this
				var index = -1;//保存存在的索引 --- 用于修改
				var order = that.OrderGoodsList
				console.log('添加的商品')
				console.log(Goods)
				console.log('存在的商品')
				console.log(order)
				// return
				for(var i in order){
					console.log('-------这是对比HOME---------');
					console.log('这是商品ID', "存在" + order[i]["GoodsID"], "添加" + Goods["GoodsID"]);
					console.log('这是商品名称', "存在" + order[i]["GoodsName"], "添加" + Goods["GoodsName"]);
					console.log('这是单位', "存在" + order[i]["UnitID"], "添加" + Goods["UnitID"]);
					console.log('这是仓库', "存在" + order[i]["StoreID"], "添加" + Goods["StoreID"]);
					console.log('这是赠品', "存在" + order[i]["IsGift"], "添加" + Goods["IsGift"]);
					console.log('这是批号', "存在" + that.isnulls(order[i]["BatchNo"]), "添加" + that.isnulls(Goods["BatchNo"]))
					console.log('这是单价', "存在" + parseFloat(order[i]["Price"]), "添加" + parseFloat(Goods["Price"]));
					console.log('这是税率', "存在" + order[i]["Tax"], "添加" + Goods["Tax"]);
					console.log('这是折扣', "存在" + order[i]["Discount"], "添加" + Goods["Discount"]);
					console.log('这是生产日期', "存在" + that.isnulls(that.timesubstr(order[i]["ProductionDate"])), "添加" + that.isnulls(that.timesubstr(Goods["ProductionDate"])))
					console.log('这是有效日期', "存在" + that.isnulls(that.timesubstr(order[i]["validityDate"])), "添加" + that.isnulls(that.timesubstr(Goods["validityDate"])))
					if(order[i]["GoodsName"] == Goods["GoodsName"] 
					   && order[i]["GoodsID"] == Goods["GoodsID"] 
					   && order[i]["StoreID"] == Goods["StoreID"]
					   && order[i]["UnitID"] == Goods["UnitID"]
					   && order[i]["IsGift"] == Goods["IsGift"]
					   && that.isnulls(order[i]["BatchNo"]) == that.isnulls(Goods["BatchNo"])
					   && parseFloat(order[i]["Price"]) == parseFloat(Goods["Price"])
					   && order[i]["Tax"] == Goods["Tax"]
					   && order[i]["Discount"] == Goods["Discount"]
					   && that.isnulls(that.timesubstr(order[i]["ProductionDate"])) == that.isnulls(that.timesubstr(Goods["ProductionDate"]))
					   && that.isnulls(that.timesubstr(order[i]["validityDate"])) == that.isnulls(that.timesubstr(Goods["validityDate"]))
						){
						status = true
						index = i
					}
					// if(that.OrderGoodsList[i]["GoodsID"] == Goods["GoodsID"] 
					// && that.OrderGoodsList[i]["UnitID"] == Goods["UnitID"]
					// && that.OrderGoodsList[i]["StoreID"] == Goods["StoreID"]
					// && that.OrderGoodsList[i]["IsGift"] == Goods["IsGift"]
					// && that.OrderGoodsList[i]["BatchNo"] == Goods["BatchNo"]){
					// 	status = true
					// 	index = i
					// }
				}
				// return
				if(status == true){
					//需要单独赋值
					that.OrderGoodsList[index]["StoreID"] = Goods["StoreID"] //仓库
					that.OrderGoodsList[index]["stockName"] = Goods["stockName"] //仓库名称
					that.OrderGoodsList[index]["UnitID"] = Goods["UnitID"] //单位
					that.OrderGoodsList[index]["IsGift"] = Goods["IsGift"]  //赠品
					that.OrderGoodsList[index]["BatchNo"] = Goods["BatchNo"] //批号
					that.OrderGoodsList[index]["ProductionDate"] = Goods["ProductionDate"] //生产日期
					that.OrderGoodsList[index]["validityDate"] = Goods["validityDate"]//到期日期
					that.OrderGoodsList[index]["Tax"] = Goods["Tax"]  //税率
					that.OrderGoodsList[index]["Price"] = parseFloat(Goods["Price"]) //单价
					that.OrderGoodsList[index]["Discount"] = Goods["Discount"]//折扣
					that.OrderGoodsList[index]["Qty"] =  (parseFloat(that.OrderGoodsList[index]["Qty"])+parseFloat(Goods["Qty"]))  //数量
					that.OrderGoodsList[index]["Remark"] = Goods["Remark"] //数量
					that.OrderGoodsList[index]["Amount"] = parseFloat(parseFloat(that.OrderGoodsList[index]["Amount"])+parseFloat(Goods["Amount"])).toFixed(2)  //金额
				}else{
					that.OrderGoodsList.push(Goods)
				}
				
				that.source_Good()
			},

			hideModal() {
				//console.log(222)
				this.modalName = null
			},

			//计算折扣后的总金额
			// compuTaxMoney(item) {
			// 	let PFPrice = parseFloat(item.PFPrice) * parseFloat(item.Qty) * (parseFloat(item.Discount) / 100) * (1 + parseFloat(
			// 		item.Tax) / 100);
			// 	return PFPrice;
			// },
			//保存单据
			AddBillOrder() {
				var that = this;
				console.log(this.OrderGoodsList)
				// return
				if (that.checkdata.BillNo == "" || that.checkdata.BillNo == undefined) {
					GetApi.showTip("单号不能为空");
					return
				} else if (that.checkdata.BillTime == "" || that.checkdata.BillTime == undefined) {
					GetApi.showTip("开单时间不能为空")
					return
				} else if (that.checkdata.ClientID == "" || that.checkdata.ClientID == undefined) {
					GetApi.showTip("供应商不能为空")
					return
				} else if (that.checkdata.StoreID == "" || that.checkdata.StoreID == undefined) {
					GetApi.showTip("仓库不能为空")
					return
				} else if (that.checkdata.EmpID == "" || that.checkdata.EmpID == undefined) {
					GetApi.showTip("业务员不能为空")
					return
				} else {
					let ClientID = uni.getStorageSync("UserCode");
					let CreateName = uni.getStorageSync("UserName");
					// let Total = 0;
					// this.OrderGoodsList.forEach((item, index) => {
					// 	Total += this.compuTaxMoney(item);
					// });
					let CreateID = uni.getStorageSync("UserCode");
					let Save_M_Data_Json = {
						BillNo: that.checkdata.BillNo,
						BillTime: GetApi.splitdate(that.checkdata.BillTime),
						ClientID: that.checkdata.ClientID,
						StoreID: that.checkdata.StoreID,
						EmpID: that.checkdata.EmpID,
						Amount: that.GoodPrice +" ", 
						CreateID: CreateID,
						CreateName: CreateName,
						Comment: that.BillRemark,
						SourceBillType: "3",
						// StoreID2 	// 仓库(除以下单据其他传0)// 调拨单为调入仓库// 配送申请单为申请仓库// 配送出库为配入仓库// 配送退回为配出仓库												       												
						// BankID      银行账户(销售出库单与POS单用到 其他单传0)     						
						// VIPID       会员卡ID  pos单用到其他单传0 									
						// PayMode   (销售出库单与POS单用到 其他单传字符串空值"  ")			
						// Int1   pos单 用  1正常销售   2退货  不用传0
						// String1    pos单 支付宝支付微信支付时的支付码
					};
					console.log('这是Save_M_Data_Json打印的参数')
					console.log(Save_M_Data_Json)
					// return
					var Save_D_Data_Json = [];
					var AllAmount = 0;
					this.OrderGoodsList.forEach((item, index) => {
						console.log('打印forEach的内容')
						console.log(item)
						let itemData = {
							BillType: "3",
							GoodsID: item.GoodsID+ "",
							UnitID: item.UnitID+ "",
							URate: item.urate+ "",
							Discount: item.Discount + "",
							Tax: item.Tax + "",
							Qty: item.Qty + "",
							Price: item.Price + "",
							Amount: item.Amount + "",
							Remark: item.Remark==""||item.Remark==undefined?"0":(item.Remark+""),
							String3: item.BarCode+ "",
							StoreID: item.StoreID+ "",
							// StoreID: item.StoreID == "underfind" ? _this.StoreList[_this.index3].BranchID : item.StoreID,
							SourceBillType: item.SourceBillType+ "",
							SourceBillID: item.SourceBillID+ "",
							SourceDetailID: item.SourceDetailID+ "",
							IsGift: item.IsGift+ "",
							ProductionDate:(item.ProductionDate == undefined?'':item.ProductionDate)+"" ,
							validityDate:(item.validityDate == undefined?'':item.validityDate)+"" ,
							BatchNo:(item.BatchNo== undefined?'':item.BatchNo)+"",
							// BatchNo              批号
							// Int1           pos单 用  1正常销售   2退货   不用传0
							// StoreID2  
							// IsGift    是否赠品
						};
						AllAmount + item.Amount
						Save_D_Data_Json.push(itemData);
					});
					// Save_M_Data_Json.Amount = AllAmount
					
					// console.log(data)
					//如果是引用单据的新添加 如果是查单则修改
					if (this.isquote == 1) {
						that.getnewBillNo(1,Save_M_Data_Json,Save_D_Data_Json)
						
					} else if (this.isquote == 2) {
						// 修改的id
						// data["BillID"] = this.checkdata["BillID"];
						let data = {
							BillType: 3,
							BillID:this.checkdata["BillID"],
							// Database:"FastApp"
							Save_M_Data_Json: JSON.stringify(Save_M_Data_Json),
							Save_D_Data_Json: JSON.stringify(Save_D_Data_Json)
						};
						GetApi.Change_Bill(data, function(res) {
							if (res.state) {
								if (res.data.ErrorMsg == "获取登录信息失败") {
									GetApi.showTip("登录超时");
								} else if (res.data.ErrorMsg != "") {
									GetApi.showTip(res.data.ErrorMsg);
								} else {
									that.OrderGoodsList = [];
									that.BillRemark = ''
									that.Goodnum = "0"
									that.GoodPrice = '0'
									that.checkdata = []
									GetApi.showTip("保存成功");

									if (that.isBillCheckQx) {
										that.toBillCheck(res.data.BillID);
									}
								}
							} else {
								GetApi.showTip("服务器错误!");
							}
						});
					}
					// return
				}
			},
			//关闭  选择商品  弹出层
			hideGoodModal() {
				this.isShowScanModel = null
			},
			// 日期截取
			timesubstr: function(e) {
				if (e != "" && e != undefined) {
					return e.substring(0, 10)
				}
			},
			// 如果是引用单据 则添加引用单据的数据
			details: function(id) {
				var that = this;
				let ClientID = uni.getStorageSync("UserCode");
				let CreateName = uni.getStorageSync("UserName");
				let Detailid = id;
				let data = {
					BillType: 2,
					Database: 'FastApp',
					BillID: Detailid,
				};
				GetApi.Check_Select_Bill_Detail(data, function(res) {
					if (res.state) {
						console.log(res)
						if (res.data.ErrorMsg == "获取登录信息失败") {
							GetApi.showTip("登录超时");
						} else if (res.data.ErrorMsg != "") {
							GetApi.showTip(res.data.ErrorMsg);
						} else {
							if (res.data.ResultMsg != "") {
								that.approvedlist = res.data.ResultMsg;
							}
						}
					} else {
						GetApi.showTip("服务器错误!");
					}
				});

				that.getnewBillNo(0)
			},
			//如果是引用单据需要重新获取单号
			getnewBillNo: function(e,M_Data,D_Data) {
				var that = this
				let data = {
					BillType: 3,
					Database: 'FastApp',
					IsAdd: e,
					BillDate: GetApi.splitdate(that.checkdata.BillTime)
					// BillID:Detailid,
				};
				GetApi.NewOrderNo(data, function(res) {
					if (res.state) {
						console.log(res)
						if (res.data.ErrorMsg == "获取登录信息失败") {
							GetApi.showTip("登录超时");
						} else if (res.data.ErrorMsg != "") {
							GetApi.showTip(res.data.ErrorMsg);
						} else {
							console.log(res)
							that.checkdata.BillNo = res.data.ResultMsg.BillNo
							if(e == 1){
								M_Data.BillNo = that.checkdata.BillNo
								let data = {
									BillType: 3,
									// BillID:this.checkdata["BillID"],
									// Database:"FastApp"
									Save_M_Data_Json: JSON.stringify(M_Data),
									Save_D_Data_Json: JSON.stringify(D_Data)
								};
								GetApi.Add_Bill(data, function(res) {
									if (res.state) {
										if (res.data.ErrorMsg == "获取登录信息失败") {
											GetApi.showTip("登录超时");
										} else if (res.data.ErrorMsg != "") {
											GetApi.showTip(res.data.ErrorMsg);
										} else {
											that.OrderGoodsList = [];
											that.BillRemark = ''
											that.Goodnum = "0"
											that.GoodPrice = '0'
											that.checkdata = []
											GetApi.showTip("保存成功");
								            
											if (that.isBillCheckQx) {
												that.toBillCheck(res.data.BillID)
											}
										}
									} else {
										GetApi.showTip("服务器错误!");
									}
								});
							}
						}
					} else {
						GetApi.showTip("服务器错误!");
					}
				});
			},
			// 如果是查单
			selectbill: function(e) {
				var that = this;
				let ClientID = uni.getStorageSync("UserCode");
				let CreateName = uni.getStorageSync("UserName");
				let Detailid = e;
				let data = {
					BillType: 3,
					Database: 'FastApp',
					BillID: Detailid,
				};
				GetApi.Select_Bill_Detail(data, function(res) {
					if (res.state) {
						console.log(res)
						if (res.data.ErrorMsg == "获取登录信息失败") {
							GetApi.showTip("登录超时");
						} else if (res.data.ErrorMsg != "") {
							GetApi.showTip(res.data.ErrorMsg);
						} else {
							that.approvedlist = res.data.ResultMsg;
						}
					} else {
						GetApi.showTip("服务器错误!");
					}
				});
				console.log(e)
			},
			//源单商品与验单商品合并
			source_Good: function() {
				var that = this
				var Goodlist = that.OrderGoodsList;
				var sourceGood = that.approvedlist
				console.log('合并')
				console.log(Goodlist)
				console.log(sourceGood)
				// return
				for (var i in Goodlist) {
					var tmp = false
					var SourceBillType = '';
					var SourceDetailID = '';
					var SourceBillID = '';
					var hasqty = 0;
					var pr = 0;
					for (var j in sourceGood) {
						sourceGood[j]["IsGift"] = sourceGood[j]["IsGift"] == "0" || sourceGood[j]["IsGift"] == false?"0":"1"
						console.log('-------这是对比HOME---------')
						console.log('这是商品ID', "选中" + Goodlist[i]["GoodsID"], "源单" + sourceGood[j]["GoodsID"])
						// console.log('这是商品名称', "源单" + Goodlist[i]["GoodsName"], "选中" + sourceGood[j]["GoodsName"])
						console.log('这是单位', "选中" + Goodlist[i]["UnitID"], "源单" + sourceGood[j]["UnitID"])
						console.log('这是仓库', "选中" + Goodlist[i]["StoreID"], "源单" + sourceGood[j]["StoreID"])
						console.log('这是赠品', "选中" + Goodlist[i]["IsGift"], "源单" + sourceGood[j]["IsGift"])
						console.log('这是批号', "选中" + that.isnulls(Goodlist[i]["BatchNo"]), "源单" + that.isnulls(sourceGood[j]["BatchNo"]))
						console.log('这是单价', "选中" + parseFloat(Goodlist[i]["Price"]), "源单" + parseFloat(sourceGood[j]["Price"]))
						console.log('这是税率', "选中" + Goodlist[i]["Tax"], "源单" + sourceGood[j]["Tax"])
						console.log('这是折扣', "选中" + Goodlist[i]["Discount"], "源单" + sourceGood[j]["Discount"])
						console.log('这是生产日期', "选中" + that.isnulls(that.timesubstr(Goodlist[i]["validityDate"])), "源单" + that.isnulls(
							that.timesubstr(sourceGood[j]["validityDate"])))
						console.log('这是有效日期', "选中" + that.isnulls(that.timesubstr(Goodlist[i]["ProductionDate"])), "源单" + that.isnulls(
							that.timesubstr(sourceGood[j]["ProductionDate"])))
						console.log('-------这是对比END----------')
						if (Goodlist[i]["GoodsID"] == sourceGood[j]["GoodsID"] &&
							Goodlist[i]["UnitID"] == sourceGood[j]["UnitID"] &&
							Goodlist[i]["StoreID"] == sourceGood[j]["StoreID"] &&
							Goodlist[i]["IsGift"] == sourceGood[j]["IsGift"] &&
							that.isnulls(Goodlist[i]["BatchNo"]) == that.isnulls(sourceGood[j]["BatchNo"]) &&
							parseFloat(Goodlist[i]["Price"]) == parseFloat(sourceGood[j]["Price"]) &&
							Goodlist[i]["Tax"] == sourceGood[j]["Tax"] &&
							Goodlist[i]["Discount"] == sourceGood[j]["Discount"] &&
							that.isnulls(that.timesubstr(Goodlist[i]["validityDate"])) == that.isnulls(that.timesubstr(sourceGood[j][
								"validityDate"
							])) &&
							that.isnulls(that.timesubstr(Goodlist[i]["ProductionDate"])) == that.isnulls(that.timesubstr(sourceGood[j][
								"ProductionDate"
							]))
							// parseFloat(arrays[i]['Price']) == parseFloat(sourcedata[j]["Price"]) &&
							// parseFloat(arrays[i]['Tax']) == parseFloat(sourcedata[j]["Tax"]) &&
							// parseFloat(arrays[i]['Discount']) == parseFloat(sourcedata[j]["Discount"]) &&
							// arrays[i]['validityDate'] == sourcedata[j]["validityDate"] &&
							// arrays[i]['ProductionDate'] == sourcedata[j]["ProductionDate"]
						) {
							tmp = true;
							console.log(sourceGood[j]["BillType"])
							console.log(sourceGood[j]["DetailID"])
							console.log(sourceGood[j]["BillID"])
							SourceBillType = sourceGood[j]["BillType"];
							SourceDetailID = sourceGood[j]["DetailID"];
							SourceBillID = sourceGood[j]["BillID"];
							if(that.isquote == 1){
								hasqty = Number(sourceGood[j]["UNQTY"]);
							}else{
								hasqty = Number(sourceGood[j]["Qty"]);
							}
							console.log(sourceGood[j]["Price"])
							console.log('最近价格')
							pr = Number(sourceGood[j]["Price"]);
						}
					}
					if (tmp == true) {
						Goodlist[i]["SourceBillType"] = SourceBillType;
						Goodlist[i]["SourceDetailID"] = SourceDetailID;
						Goodlist[i]["SourceBillID"] = SourceBillID;
						that.$set(Goodlist[i], 'hasqty', hasqty);
						// that.$set(Goodlist[i],'Price',pr);
						// if(that.isquote == 1){
						// 	that.$set(Goodlist[i],'Price',pr);
						// }

					} else {
						Goodlist[i]["SourceBillType"] = "0";
						Goodlist[i]["SourceDetailID"] = "0";
						Goodlist[i]["SourceBillID"] = "0";
						that.$set(Goodlist[i], 'hasqty', 0);
					}

				}
				//验单数
				var num = 0;
				for (var i in Goodlist) {
					num = parseFloat(num) + parseFloat(Goodlist[i].Qty)
				}
				that.noapproved = num;
				that.OrderGoodsList = Goodlist;
				this.imputed()
				console.log('执行了')
				console.log(Goodlist)
			},
			// isnulls: function(e) {
			// 	return e == "" || typeof e == 'undefined' ? "" : e
			// },
			onNavigationBarButtonTap(e) {
				var that = this
				const index = e.index;
				if (index === 0) {
					that.$refs.Drawer.open(this.checkdata.BillNo == "" || this.checkdata.BillNo == undefined ? false : true, this.isquote);
				}
			},
			// 远程打印
			RemotePrint(e) {
				console.log('点击了远程打印')
				console.log(e)
				console.log(this.checkdata)
				var data = {};
				var Save_M_Data_Json = {};
				Save_M_Data_Json = {
					Order_Number: this.checkdata.BillNo,
					BillName: '采购退货单',
					Printer: this.CreateName,
					BillID: this.checkdata.BillID,
					PrintNum: e.detail.printNum + "",
					PrintPCNumber: e.detail.checkd + ""
				};
				data = {
					Save_M_Data_Json: JSON.stringify(Save_M_Data_Json)
				}
				var that = this
				GetApi.Add_Android_Print(data, function(res) {
					if (res.state) {
						if (res.data.ErrorMsg == '获取登录信息失败') {
							GetApi.showTip("登录超时");
						} else if (res.data.ErrorMsg != "") {
							GetApi.showTip(res.data.ErrorMsg);
						} else {
							GetApi.showTip("已发送打印指令");
							var config = that.GetConfig()
							console.log(config)
							console.log(config.long)
							//等于0表示  ----打印后询问是否审核单据
							if (config.long == 0) {
								GetApi.showConfirm("是否审核单据", function(result) {
									if (result) {
										that.toBillCheck();
									}
								})
							} else {
								that.toBillCheck()
							}
						}
					}
				})
			},
			//审核单据
			toBillCheck(BillID) {
				var that = this;
				let data = {
					BillType: '3',
					BillID: BillID || this.checkdata.BillID,
					BillName: '采购退货单'
				};
				console.log(this.checkdata)
				GetApi.Bill_Check(data, function(res) {
					if (res.state) {
						if (res.data.ErrorMsg == '获取登录信息失败') {
							GetApi.showTip("登录超时!");
						} else if (res.data.ErrorMsg != "") {
							GetApi.showTip(res.data.ErrorMsg);
						} else {
							// that.isBillCheckSuc[that.isBillCheck] = checkCountList[that.isBillCheck];
							// that.isBillCheck++;
							GetApi.showTip("审核成功");
							if(that.isquote == 1){
								that.details(that.checkdata.BillID)
							}else{
								that.selectbill(that.checkdata.BillID)
							}
						}
					} else {

					}
					//关闭弹出框
					that.$refs.Drawer.cancelModel()
					that.$refs.Drawer.hideModal()
					// that.toBillCheck(checkCountList, index, countSize);
				})
			},
			// 读取配置
			GetConfig() {
				return JSON.parse(uni.getStorageSync("v1_setting", ""))
			},
		}
	}
</script>

<style>
	@import url("/Purchasereturn.css");

	page {
		background-color: #EEEEEE;
		padding-bottom: 0upx;
		height: 100%;
	}
</style>
